package org.opens.lambda.parallel;

import java.util.concurrent.RecursiveAction;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 简介:
 *      RecursiveAction是一个无返回值的Fork Join对象, 需要用户自定义区处理结果集.
 * 说明:
 *      1. 此处是使用一个静态内部类来操作的.
 */
public class AccmulatorRecursiveAction extends RecursiveAction {

    private final int start;

    private final int end;

    private final int[] data;

    private final int LIMIT = 3;

    public AccmulatorRecursiveAction(int start, int end, int[] data) {
        this.start = start;
        this.end = end;
        this.data = data;
    }

    @Override
    protected void compute() {
        if(( end - start) <= LIMIT) {
            int result = 0;
            for(int i = start; i < end; i++) {
                //result += data[i];
                AccumulatorHelper.accumulate(data[i]);
            }
        } else {
            int middle = ( start + end ) / 2;
            AccmulatorRecursiveAction left = new AccmulatorRecursiveAction(start, middle, data);
            AccmulatorRecursiveAction right = new AccmulatorRecursiveAction(middle, end, data);

            left.fork();
            right.fork();

            left.join();
            right.join();
        }
    }

    public int getResult() {
        return AccumulatorHelper.getResult();
    }

    static class AccumulatorHelper {

        private static final AtomicInteger result = new AtomicInteger(0);

        /**
         * 功能:
         *      进行值的累加.
         * 注意:
         *      1. 设置成default修饰符为包可见.
         */
        static void accumulate(int value) {
            result.getAndAdd(value);
        }

        public static int getResult() {
            return result.get();
        }

        static void reset() {
            result.set(0);
        }
    }
}
